package com.zzu.base.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzu.base.common.enums.ResultStatusEnum;
import com.zzu.base.common.pojo.ResultResponse;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class AuthenticationExceptionHandler implements AuthenticationEntryPoint {

    @Resource
    ObjectMapper objectMapper;
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        // 设置响应状态码
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json;charset=UTF-8");

        // 创建与全局异常处理器一致的响应格式
        ResultResponse<String> result = ResultResponse.error(
                authException.getMessage(),       // 错误消息
                ResultStatusEnum.UNAUTHORIZED // 自定义状态枚举
        );

        // 记录错误日志
        log.error("认证失败: {}", authException.getMessage());

        // 输出 JSON 响应
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
